package com.mhc.suzuki.controller;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.form.DownloadForm;
import com.mhc.suzuki.service.DownloadService;
import com.mhc.suzuki.vo.DownloadFileInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Optional;

/**
 * @author kanon
 * @create 2017-09-08 11:52
 **/
@Slf4j
@RestController
@RequestMapping(value = "/download")
public class DownloadController {

    @Autowired
    private DownloadService downloadService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<Resource> downloadBackupFile(@AuthenticationPrincipal User logedUser, DownloadForm downloadForm) {
        log.info("附件下载开始");
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        ResponseEntity<Resource> resourceResponseEntity = null;
        if (userOptional.isPresent()) {
            logedUser.setStaffName(logedUser.getStaffName());
            try {
                DownloadFileInfoVO fileInfo = downloadService.downloadFile(downloadForm.getOrderNOList(), logedUser.getStaffName());
                resourceResponseEntity = downloadResponse(fileInfo);
            } catch (Exception e) {
                log.error("Exception", e);
            }
        }
        log.info("附件下载完成");
        return resourceResponseEntity;
    }

    protected ResponseEntity<Resource> downloadResponse(
            DownloadFileInfoVO fileInfo) {
        File file = fileInfo.getFile();
        String fileName = fileInfo.getFileName();
        Resource body = new FileSystemResource(file);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String header = request.getHeader("User-Agent").toUpperCase();
        HttpStatus status = HttpStatus.CREATED;
        try {
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
                fileName = fileName.replace("+", "%20");    // IE下载文件名空格变+号问题
                status = HttpStatus.OK;
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException", e);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentLength(file.length());

        return new ResponseEntity<>(body, headers, status);
    }

}
